package utils.common;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class EmailUtil {

	// 发件人电子邮箱
	private String from;
	// 发件人电子邮箱密码
	private String pass;
	// 指定发送邮件的主机为 smtp.qq.com
	private String host; // 邮件服务器

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * 
	 * 进行base64加密，防止中文乱码
	 * 
	 */

	@SuppressWarnings("unused")
	private static String changeEncode(String str) {

		try {

			str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"), "UTF-8", "B"); // "B"代表Base64

		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

		}

		return str;

	}

	/**
	 * 发送带附件的邮件
	 */
	//public boolean sendMail(String receive, String subject, String msg, File file) throws GeneralSecurityException, IOException {
	public boolean sendMail(String receive, String subject, String msg, String fileName, byte[] bytes, String type) throws GeneralSecurityException, IOException {
		if (StrUtil.isEmpty(receive)) {
			return false;
		}

		// 获取系统属性
		Properties properties = System.getProperties();

		// 设置邮件服务器
		properties.setProperty("mail.smtp.host", host);

		properties.put("mail.smtp.auth", "true");
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", sf);
		// 获取默认session对象
		Session session = Session.getDefaultInstance(properties, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
				return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
			}
		});

		try {
			// 创建默认的 MimeMessage 对象
			MimeMessage message = new MimeMessage(session);

			// Set From: 头部头字段
			message.setFrom(new InternetAddress(from));

			// Set To: 头部头字段
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));

			// Set Subject: 主题文字
			message.setSubject(subject);

			// 创建消息部分
			BodyPart messageBodyPart = new MimeBodyPart();

			// 消息
			//messageBodyPart.setText(msg);
            messageBodyPart.setContent(msg, "text/html;charset=utf-8");

			// 创建多重消息
			Multipart multipart = new MimeMultipart();

			// 设置文本消息部分
			multipart.addBodyPart(messageBodyPart);

			// 附件部分
//			messageBodyPart = new MimeBodyPart();
//			File file= new File("C:\\Users\\zhanyonghu\\Desktop\\spring-mvc.xml");
//			inputstreamtofile(in,file );
			//String filename = file.getPath();
			// 设置要发送附件的文件路径
			// DataSource source = new FileDataSource(filename);

            // 设置要发送附件的文件
            messageBodyPart = new MimeBodyPart();
			messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, type)));

			// 处理附件名称中文（附带文件路径）乱码问题
			messageBodyPart.setFileName(MimeUtility.encodeText(fileName));
			// 加入到主体中
			multipart.addBodyPart(messageBodyPart);

			// 发送完整消息
			message.setContent(multipart);

			// 发送消息
			Transport.send(message);
			// System.out.println("Sent message successfully....");
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		/*catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
		return false;
	}

	/**
	 * 流转成文件
	 * 
	 * @param ins
	 * @param file
	 * @throws IOException
	 */
	public static void inputstreamtofile(InputStream ins, File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
	}

	public static void main(String[] args) throws GeneralSecurityException, IOException {

		// File file = new File("C:\Program Files (x86)\apache-tomcat-8.5.34\temp\A9OwRml9mvWLJzvIAvJ\信息咨询服务意向书1套房产9.4.pdf");
		// InputStream in = new FileInputStream(file);
		// sendMail("719189721@qq.com", "qweqwe", "<p>这是一个测试邮件</p>", in);
	}

}